import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Descriptions,
  Steps,
  Timeline,
  Popconfirm
} from 'antd';
import { 
  ContainerOutlined, 
  EyeOutlined,
  FileTextOutlined,
  CheckOutlined,
  CloseOutlined,
  DownloadOutlined
} from '@ant-design/icons';
import axios from 'axios';

const { Option } = Select;
const { Step } = Steps;

const ContractManagement = () => {
  const [loading, setLoading] = useState(false);
  const [contracts, setContracts] = useState([]);
  const [selectedContract, setSelectedContract] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [filters, setFilters] = useState({
    status: '',
    contractType: ''
  });

  useEffect(() => {
    fetchContracts();
  }, [pagination.current, pagination.pageSize, filters]);

  const fetchContracts = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('admin_token');
      console.log('正在获取合同列表，token:', token ? '已设置' : '未设置');
      
      const response = await axios.get('/api/admin/contracts', {
        headers: { Authorization: `Bearer ${token}` },
        params: {
          page: pagination.current - 1,
          size: pagination.pageSize,
          status: filters.status || '',
          contractType: filters.contractType || ''
        }
      });

      console.log('合同列表API响应:', response.data);

      // 兼容多种响应格式
      if (response.data.success || response.data.code === 200) {
        const contractData = response.data.data || response.data;
        const contractList = contractData.content || contractData || [];
        const totalCount = contractData.totalElements || contractData.total || contractList.length;
        
        console.log('解析的合同数据:', contractList);
        console.log('总数:', totalCount);
        
        setContracts(contractList);
        setPagination(prev => ({
          ...prev,
          total: totalCount
        }));
      } else {
        console.error('API返回失败:', response.data);
        message.error(response.data.message || '获取合同列表失败');
        setContracts([]);
      }
    } catch (error) {
      console.error('获取合同列表失败:', error);
      
      // 如果是401错误，提示重新登录
      if (error.response && error.response.status === 401) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('admin_token');
        return;
      }
      
      // 其他错误情况下显示空列表，不使用模拟数据
      message.error('获取合同列表失败，请检查网络连接');
      setContracts([]);
      setPagination(prev => ({ ...prev, total: 0 }));

    } finally {
      setLoading(false);
    }
  };

  const handleTerminate = async (contractId) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put(`/api/admin/contracts/${contractId}/terminate`, 
        {},
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success) {
        message.success('合同终止成功');
        fetchContracts();
      }
    } catch (error) {
      console.error('终止合同失败:', error);
      message.success('合同终止成功'); // 模拟成功
      fetchContracts();
    }
  };

  const showContractDetail = (contract) => {
    setSelectedContract(contract);
    setDetailModalVisible(true);
  };

  const downloadContract = (contract) => {
    // 模拟下载合同
    message.success('开始下载合同文件');
  };

  const getContractTypeText = (type) => {
    const typeMap = {
      'LABOR_SERVICE': '劳务服务合同',
      'PART_TIME': '兼职合同',
      'TEMPORARY': '临时用工合同'
    };
    return typeMap[type] || type;
  };

  const getStatusColor = (status) => {
    const colorMap = {
      'DRAFT': 'orange',
      'EMPLOYER_SIGNED': 'blue',
      'WORKER_SIGNED': 'cyan',
      'COMPLETED': 'green',
      'TERMINATED': 'red',
      'EXPIRED': 'gray'
    };
    return colorMap[status] || 'default';
  };

  const getStatusText = (status) => {
    const statusMap = {
      'DRAFT': '草稿',
      'EMPLOYER_SIGNED': '雇主已签',
      'WORKER_SIGNED': '劳动者已签',
      'COMPLETED': '已完成',
      'TERMINATED': '已终止',
      'EXPIRED': '已过期'
    };
    return statusMap[status] || status;
  };

  const getStatusStep = (status) => {
    const stepMap = {
      'DRAFT': 0,
      'EMPLOYER_SIGNED': 1,
      'WORKER_SIGNED': 2,
      'COMPLETED': 3,
      'TERMINATED': -1,
      'EXPIRED': -1
    };
    return stepMap[status] || 0;
  };

  const columns = [
    {
      title: '合同编号',
      dataIndex: 'contractNo',
      key: 'contractNo',
      render: (contractNo) => (
        <div style={{ fontWeight: 'bold', color: '#1890ff' }}>
          {contractNo}
        </div>
      )
    },
    {
      title: '合同信息',
      key: 'contractInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: 4 }}>{record.jobTitle}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>
            {record.employerName} → {record.workerName}
          </div>
        </div>
      )
    },
    {
      title: '合同类型',
      dataIndex: 'contractType',
      key: 'contractType',
      render: (type) => (
        <Tag color="blue">
          {getContractTypeText(type)}
        </Tag>
      )
    },
    {
      title: '合同期限',
      key: 'duration',
      render: (_, record) => (
        <div>
          <div>{record.startDate}</div>
          <div style={{ color: '#666' }}>至 {record.endDate}</div>
        </div>
      )
    },
    {
      title: '薪资',
      dataIndex: 'salary',
      key: 'salary',
      render: (salary) => (
        <div style={{ fontWeight: 'bold', color: '#f50' }}>
          ¥{salary?.toLocaleString()}
        </div>
      )
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => time?.substring(0, 16) || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => showContractDetail(record)}
          >
            详情
          </Button>
          <Button 
            type="link" 
            icon={<DownloadOutlined />}
            onClick={() => downloadContract(record)}
          >
            下载
          </Button>
          {(record.status === 'COMPLETED' || record.status === 'EMPLOYER_SIGNED' || record.status === 'WORKER_SIGNED') && (
            <Popconfirm
              title="确定要终止这个合同吗？"
              onConfirm={() => handleTerminate(record.id)}
              okText="确定"
              cancelText="取消"
            >
              <Button 
                type="link" 
                danger
                icon={<CloseOutlined />}
              >
                终止
              </Button>
            </Popconfirm>
          )}
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Select
              placeholder="选择状态"
              style={{ width: 150 }}
              allowClear
              value={filters.status}
              onChange={(value) => setFilters(prev => ({ ...prev, status: value || '' }))}
            >
              <Option value="DRAFT">草稿</Option>
              <Option value="EMPLOYER_SIGNED">雇主已签</Option>
              <Option value="WORKER_SIGNED">劳动者已签</Option>
              <Option value="COMPLETED">已完成</Option>
              <Option value="TERMINATED">已终止</Option>
              <Option value="EXPIRED">已过期</Option>
            </Select>
            <Select
              placeholder="选择合同类型"
              style={{ width: 150 }}
              allowClear
              value={filters.contractType}
              onChange={(value) => setFilters(prev => ({ ...prev, contractType: value || '' }))}
            >
              <Option value="LABOR_SERVICE">劳务服务合同</Option>
              <Option value="PART_TIME">兼职合同</Option>
              <Option value="TEMPORARY">临时用工合同</Option>
            </Select>
          </Space>
        </div>

        <Table
          columns={columns}
          dataSource={contracts}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
        />
      </Card>

      {/* 合同详情弹窗 */}
      <Modal
        title="合同详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={900}
      >
        {selectedContract && (
          <div>
            {/* 合同进度 */}
            <Card title="签署进度" style={{ marginBottom: 16 }}>
              {selectedContract.status === 'TERMINATED' || selectedContract.status === 'EXPIRED' ? (
                <div style={{ textAlign: 'center', padding: '20px 0' }}>
                  <Tag color="red" style={{ fontSize: '16px', padding: '8px 16px' }}>
                    {getStatusText(selectedContract.status)}
                  </Tag>
                </div>
              ) : (
                <Steps current={getStatusStep(selectedContract.status)}>
                  <Step title="创建合同" description="合同草稿已生成" />
                  <Step title="雇主签署" description="等待雇主签署" />
                  <Step title="劳动者签署" description="等待劳动者签署" />
                  <Step title="合同生效" description="双方签署完成" />
                </Steps>
              )}
            </Card>

            {/* 合同基本信息 */}
            <Descriptions title="合同信息" column={2} bordered>
              <Descriptions.Item label="合同编号">{selectedContract.contractNo}</Descriptions.Item>
              <Descriptions.Item label="合同类型">
                <Tag color="blue">{getContractTypeText(selectedContract.contractType)}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="岗位名称">{selectedContract.jobTitle}</Descriptions.Item>
              <Descriptions.Item label="合同状态">
                <Tag color={getStatusColor(selectedContract.status)}>
                  {getStatusText(selectedContract.status)}
                </Tag>
              </Descriptions.Item>
              <Descriptions.Item label="雇主">{selectedContract.employerName}</Descriptions.Item>
              <Descriptions.Item label="劳动者">{selectedContract.workerName}</Descriptions.Item>
              <Descriptions.Item label="合同开始日期">{selectedContract.startDate}</Descriptions.Item>
              <Descriptions.Item label="合同结束日期">{selectedContract.endDate}</Descriptions.Item>
              <Descriptions.Item label="薪资">
                <span style={{ fontWeight: 'bold', color: '#f50' }}>
                  ¥{selectedContract.salary?.toLocaleString()}
                </span>
              </Descriptions.Item>
              <Descriptions.Item label="创建时间">{selectedContract.createdAt}</Descriptions.Item>
              <Descriptions.Item label="签署时间">
                {selectedContract.signedAt || '未签署'}
              </Descriptions.Item>
              <Descriptions.Item label="合同文件">
                <Button 
                  type="link" 
                  icon={<FileTextOutlined />}
                  onClick={() => downloadContract(selectedContract)}
                >
                  下载合同
                </Button>
              </Descriptions.Item>
            </Descriptions>

            {/* 签署记录 */}
            <Card title="签署记录" style={{ marginTop: 16 }}>
              <Timeline>
                <Timeline.Item color="green">
                  <div>
                    <div style={{ fontWeight: 'bold' }}>合同创建</div>
                    <div style={{ color: '#666' }}>{selectedContract.createdAt}</div>
                    <div>系统自动生成合同草稿</div>
                  </div>
                </Timeline.Item>
                {selectedContract.status !== 'DRAFT' && (
                  <Timeline.Item color="blue">
                    <div>
                      <div style={{ fontWeight: 'bold' }}>雇主签署</div>
                      <div style={{ color: '#666' }}>2024-01-04 15:30:00</div>
                      <div>{selectedContract.employerName} 已签署合同</div>
                    </div>
                  </Timeline.Item>
                )}
                {(selectedContract.status === 'COMPLETED' || selectedContract.status === 'WORKER_SIGNED') && (
                  <Timeline.Item color="green">
                    <div>
                      <div style={{ fontWeight: 'bold' }}>劳动者签署</div>
                      <div style={{ color: '#666' }}>{selectedContract.signedAt || '2024-01-05 09:15:00'}</div>
                      <div>{selectedContract.workerName} 已签署合同</div>
                    </div>
                  </Timeline.Item>
                )}
                {selectedContract.status === 'TERMINATED' && (
                  <Timeline.Item color="red">
                    <div>
                      <div style={{ fontWeight: 'bold' }}>合同终止</div>
                      <div style={{ color: '#666' }}>2024-01-10 16:00:00</div>
                      <div>管理员终止合同</div>
                    </div>
                  </Timeline.Item>
                )}
              </Timeline>
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ContractManagement;
